<template>
  <el-dialog title="新增任务" :visible.sync="showDialog" width="600px" @close="cancelSubmit">
    <el-form :model="formData" ref="formData" label-width="100px" size="small">
      <p class="title">
        数据采集
      </p>
      <el-row style="padding-left:70px;">
        <el-form-item label="单位名称:" prop="companyCode">
          <el-select v-model="formData.companyCode" size="small" placeholder="请选择单位" style="width:350px;" @change="companyChange" filter clearable>
            <el-option v-for="item in tree" :label="item.companyName" :value="item.companyCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场站名称:" prop="stationCode">
          <el-select style="width:350px;" v-model="formData.stationCode" placeholder="请选择场站" clearable filter>
            <el-option v-for="item in stationList" :label="item.stationName" :value="item.stationCode" :key="item.stationCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件:" prop="fileName" :rules="{ required: true, message: '请选择上传文件只支持zip rar格式', trigger: 'change'}">
<!--          <el-upload-->
<!--            ref="upload"-->
<!--            class="upload-demo"-->
<!--            action="https://jsonplaceholder.typicode.com/posts/"-->
<!--            :on-change="handleChange"-->
<!--            :file-list="fileList"-->
<!--            :multiple="false"-->
<!--            :show-file-list="false"-->
<!--            :auto-upload="false">-->
          <div style="position: relative">
            <input style="position: absolute; top: 0; left: 0; width: 100%; z-index: 999; opacity: 0" ref="upload" type="file" @change="handleChange" multiple webkitdirectory></input>
            <el-input style="width:350px;" size="small" prefix-icon="el-icon-folder-add" placeholder="请选择文件" v-model="formData.fileName" @focusin="$refs.upload.click()"></el-input>
          </div>

          <!--          </el-upload>-->
        </el-form-item>
        <el-form-item label="文件描述:"  prop="stationName">
          <el-input
            type="textarea"
            autosize
            placeholder="请输入文件描述"
            style="width:350px;"
            :rows="2"
            v-model="formData.remark">
          </el-input>
        </el-form-item>
      </el-row>
      <p class="title">
        模型选择
      </p>
      <el-row style="padding-left:70px;">
        <el-form-item label="诊断模型:"  prop="stationName" style="height:unset;">
          <div style="width:350px; max-height:400px; overflow-y:auto;border:1px solid rgba(229,229,229,1);border-radius:4px; padding:0 10px;">
            <el-checkbox label="全选" @change="handleCheckAllChange" v-model="checkAll">全选</el-checkbox>
            <el-checkbox v-for="item in outerModelList" :key="item.id" :label="item.diagModelCode" @change="event => itemChange(event, item.diagModelCode)" v-model="checkedMap[item.diagModelCode]">
              <el-popover
                placement="top-start"
                width="200"
                trigger="hover"
                :content="item.remark">
                <span slot="reference">
                  {{ item.diagModelName }}
                </span>
              </el-popover>
            </el-checkbox>
          </div>
        </el-form-item>
      </el-row>
      <p class="title">
        结果推送配置
      </p>
      <el-row style="padding-left:70px;">
        <el-form-item label="推送平台:"  prop="stationName" style="height:unset;">
          <el-select :disabled="true" v-model="formData.type" size="small" placeholder="请选择推送平台" style="width:350px;" clearable multiple filterable>
            <el-option v-for="item in tree" :label="item.companyName" :value="item.companyCode"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="cancelSubmit" size="small">取 消</el-button>
      <el-button type="primary" @click="addSubmit" size="small">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import myTaskApi from "../../../../api/myTask";
  import stations from "../../../../api/stations"
  import manual from "../../../../api/manual";
  import dataSourceApi from "../../../../api/dataSourceApi";
  import eventBus from "../../../../eventBus"

  export default {
    name: "dialogEditTask",
    data() {
      return {
        showDialog: false,
        formData: {
          companyCode: "",
          stationCode: "",
          taskNumber: "",
          dataSource: 0,
          uploadTime: null,
          order: 'desc',
          fileName: ""
        },
        fileList: [],
        file: null,
        tree: [],
        stationList: [],
        checkedMap: {},
        outerModelList: [],
        checkAll: ''
      }
    },
    methods: {
      show() {
        this.showDialog = true
        this.init()
      },
      init() {
        this.formData = {
          companyCode: "",
          stationCode: "",
          taskNumber: "",
          dataSource: 0,
          uploadTime: null,
          order: 'desc',
          fileName: ""
        }
        this.file = ""
        this.checkAll = ""
        this.getCompanyList()
        this.getOuterModelList()
      },
      getOuterModelList() {
        manual.getOuterModelList().then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.outerModelList = res.data.data
            this.outerModelList.map(item => {
              this.checkedMap[item.diagModelCode] = false
            })
          }
        })
      },
      itemChange(value, target) {
        if (value) {
          this.$set(this.checkedMap, [target], true)
          let i = 0
          for (let key in this.checkedMap) {
            if (this.checkedMap[key]) {
              i++
            }
          }
          if (i === this.outerModelList.length) {
            this.checkAll = true
          }
        } else {
          this.$set(this.checkedMap, [target], false)
          this.checkAll = false
        }
        this.$forceUpdate()
      },
      handleCheckAllChange(val) {
        for (let key in this.checkedMap) {
          this.checkedMap[key] = val
        }
      },
      handleChange(file) {
        this.file = file.target.files
        console.log("file", file.target.files[0].webkitRelativePath.split("/"))
        this.file.name = file.target.files[0].webkitRelativePath.split("/")[0]
        // const isZip = file.name.split(".")[file.name.split(".").length - 1] === "zip"
        // const isRar= file.name.split(".")[file.name.split(".").length - 1] === "rar"
        // if (!isZip && !isRar) {
        //   this.$message.error('只能上传ZIP或RAR格式文件!');
        //   return
        // }
        this.formData.file = this.file
        this.formData.fileName = this.file.name
      },
      // handleRemove(file, fileList) {
      //   console.log(file, fileList, 'handleRemove');
      // },
      // handlePreview(file) {
      //   console.log(file, 'handlePreview');
      // },
      getCompanyList() {
        stations.getCompanyList().then(res => {
          if (res && res.data.code === 200) {
            this.tree = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      companyChange() {
        this.formData.stationCode = ""
        this.formData.taskNumber = ""
        this.getStationByCompany()
      },
      getStationByCompany() {
        manual.getStationByCompany({
          companyCode: this.formData.companyCode
        }).then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.stationList = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      addSubmit() {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            // 校验文件是否上传过，未上传过才允许上传
            let titleArr = []
            for (let key in this.checkedMap) {
              if (this.checkedMap[key]) {
                titleArr.push(key)
              }
            }
            this.formData.diagModelCode = titleArr.join(',')
            this.formData.title = titleArr.join(',')
            this.formData.oriFileName = this.formData.fileName
            // 生成任务编号
            dataSourceApi.insertTaskInfo({
              companyCode: this.formData.companyCode,
              stationCode: this.formData.stationCode
            }).then(res => {
              if (res && res.data.code === 200) {
                this.formData.inspectTaskCode = res.data.data.inspectTaskCode
                this.addNewTask()
                this.uploadFile()
                this.showDialog = false
              }
            }).catch(e => {
              this.$message.error({message: e.message ? e.message : e, center: true})
            })
            //   }
            // }).catch(e => {
            //     this.$message.error({message: e.message ? e.message : e, center: true})
            // })
          }
        })
      },
      addNewTask() {
        // 新增任务流
        myTaskApi.insertTaskFlow({
          companyCode: this.formData.companyCode,
          stationCode: this.formData.stationCode,
          fileDescribe: this.formData.remark,
          diagModelCode: this.formData.diagModelCode,
          inspectTaskCode: this.formData.inspectTaskCode,
          oriFileName: this.formData.oriFileName,
          taskStartTime: this.formData.taskStartTime
        }).then(res => {
          if (res && res.status === 200) {
            if (this.formData.diagModelCode && this.formData.diagModelCode !== "") {
              this.startTask()
            } else {
              this.$message.success("添加成功！")
              this.$emit("sendDialogEditTask")
              this.showDialog = false
            }
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      uploadFile() {
        eventBus.$emit("uploadTask", {
          blob: this.formData.file,
          params: this.formData
        })
      },
      startTask() {
        myTaskApi.integrationStartDiagTask({
          companyCode: this.formData.companyCode,
          stationCode: this.formData.stationCode,
          fileDescribe: this.formData.remark,
          diagModelCode: this.formData.diagModelCode,
          inspectTaskCode: this.formData.inspectTaskCode,
          taskFlowCode: this.formData.inspectTaskCode,
          oriFileName: this.formData.oriFileName,
          taskStartTime: this.formData.taskStartTime
        }).then(res => {
          this.$message.success("添加成功！")
          this.$emit("sendDialogEditTask")
          eventBus.$emit("manual", { params: { diagTaskCode: res.data.data.diagTaskCode } })
          this.showDialog = false
        }).catch(e => {
            this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      cancelSubmit() {
        this.showDialog = false
      }
    }
  }
</script>

<style scoped>

</style>
